<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
  <title>ArcGIS Draw Selection Demo</title>

  <link rel="stylesheet" href="https://js.arcgis.com/4.26/esri/themes/light/main.css" />
  <script src="https://js.arcgis.com/4.26/"></script>

  <style>
    html,
    body,
    #viewDiv {
      padding: 0;
      margin: 0;
      height: 100%;
      width: 100%;
      overflow: hidden;
    }

    body {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }

    #viewDiv {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 0;
    }

    .instructions {
      margin-bottom: 10px;
      font-size: 12px;
      color: #666;
    }

    .instructions p {
      margin: 2px 0;
    }

    .tool-bar {
      position: absolute;
      top: 15px;
      left: 15px;
      z-index: 1000;
      background: white;
      padding: 10px;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      min-width: 200px;
    }

    .tool-bar button {
      margin: 0 5px;
      padding: 5px 10px;
      background: #0066cc;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    .tool-bar button:hover {
      background: #0052a3;
    }
  </style>

  <script>
    require([
      "esri/Map",
      "esri/views/MapView",
      "esri/layers/GraphicsLayer",
      "esri/Graphic",
      "esri/geometry/Point",
      "esri/geometry/Polygon",
      "esri/views/draw/Draw",
      "esri/geometry/geometryEngine",
      "esri/geometry/support/webMercatorUtils"
    ], function (Map, MapView, GraphicsLayer, Graphic, Point, Polygon, Draw,
      geometryEngine, webMercatorUtils) {

      // 创建地图
      const map = new Map({
        basemap: "streets-vector"  // 使用矢量街道底图
      });

      // 创建视图
      const view = new MapView({
        container: "viewDiv",
        map: map,
        center: [116.4, 39.9], // 北京中心点
        zoom: 12
      });

      // 创建坐标转换函数
      function convertToWGS84(geometry) {
        try {
          // 检查是否需要转换
          if (geometry.spatialReference && geometry.spatialReference.wkid !== 4326) {
            return webMercatorUtils.webMercatorToGeographic(geometry);
          }
          return geometry;
        } catch (error) {
          console.error('坐标转换错误:', error);
          return geometry;
        }
      }

      let activeAction = null; // 添加一个变量来跟踪当前活动的绘图操作

      // 创建图层
      const graphicsLayer = new GraphicsLayer();
      const pointsLayer = new GraphicsLayer();
      map.add(graphicsLayer);
      map.add(pointsLayer);

      // 生成北京区域随机点
      function generateRandomPoints() {
        // 北京大致范围
        const bounds = {
          minLon: 116.1,
          maxLon: 116.7,
          minLat: 39.6,
          maxLat: 40.2
        };

        console.log('开始生成随机点');
        // 生成100个随机点
        for (let i = 0; i < 100; i++) {
          const lon = bounds.minLon + Math.random() * (bounds.maxLon - bounds.minLon);
          const lat = bounds.minLat + Math.random() * (bounds.maxLat - bounds.minLat);

          console.log(`生成点 ${i + 1}:`, lon, lat);
          const point = new Point({
            longitude: lon,
            latitude: lat,
            spatialReference: { wkid: 4326 }
          });

          const pointGraphic = new Graphic({
            geometry: point,
            symbol: {
              type: "simple-marker",
              color: "red",
              size: 6
            },
            attributes: {
              id: i + 1,
              name: `Point ${i + 1}`
            }
          });

          pointsLayer.add(pointGraphic);
        }
      }

      // 初始化绘图工具
      const draw = new Draw({
        view: view
      });

      // 绘图工具激活函数
      function activateDrawTool(geometryType) {
        console.log('开始绘图:', geometryType);
        // 如果有活动的绘图操作，先取消它
        if (activeAction) {
          activeAction.complete();
          activeAction = null;
        }

        // 清除之前的图形
        graphicsLayer.removeAll();
        view.graphics.removeAll();
        draw.reset();

        let action;
        switch (geometryType) {
          case 'polygon':
            action = draw.create("polygon", {
              mode: "click",
              enableCircle: false,
              enableFreehandMode: false
            });
            break;
          case 'rectangle':
            action = draw.create("rectangle", {
              mode: "click"
            });
            break;
          case 'circle':
            action = draw.create("circle", {
              mode: "click"
            });
            break;
        }

        console.log('绘图工具创建完成');
        activeAction = action;

        // 添加绘制过程中的临时图形显示
        action.on(["vertex-add", "vertex-remove", "cursor-update"], function (event) {
          // 清除之前的临时图形
          view.graphics.removeAll();

          // 添加临时图形
          if (event.vertices.length > 0) {
            let geometry;

            // 根据不同的绘制类型创建不同的几何对象
            switch (geometryType) {
              case 'polygon':
                geometry = {
                  type: "polygon",
                  rings: [event.vertices],
                  spatialReference: view.spatialReference
                };
                break;
              case 'rectangle':
                // 显示矩形
                const vertices = event.vertices;
                if (vertices.length === 2) {
                  // 最终矩形
                  const start = vertices[0];
                  const end = vertices[1];

                  const rings = [
                    [start[0], start[1]],
                    [end[0], start[1]],
                    [end[0], end[1]],
                    [start[0], end[1]],
                    [start[0], start[1]]
                  ];

                  geometry = {
                    type: "polygon",
                    rings: [rings],
                    spatialReference: view.spatialReference
                  };
                }
                break;
              case 'circle':
                if (event.vertices.length === 2) {
                  // 最终圆形
                  const center = event.vertices[0];
                  const end = event.vertices[1];

                  // 计算最终径
                  const radius = Math.sqrt(
                    Math.pow(end[0] - center[0], 2) +
                    Math.pow(end[1] - center[1], 2)
                  );

                  // 生成最终圆形
                  const numPoints = 64;
                  const rings = [];

                  for (let i = 0; i <= numPoints; i++) {
                    const angle = (i / numPoints) * 2 * Math.PI;
                    const x = center[0] + radius * Math.cos(angle);
                    const y = center[1] + radius * Math.sin(angle);
                    rings.push([x, y]);
                  }

                  geometry = {
                    type: "polygon",
                    rings: [rings],
                    spatialReference: view.spatialReference
                  };
                }
                break;
            }

            if (geometry) {
              const tempGraphic = new Graphic({
                geometry: geometry,
                symbol: {
                  type: "simple-fill",
                  color: [51, 51, 204, 0.2],
                  outline: {
                    color: [51, 51, 204],
                    width: 1
                  }
                }
              });
              view.graphics.add(tempGraphic);
            }
          }
        });

        // 更新鼠标样式
        view.container.style.cursor = "crosshair";

        // 显示操作提示
        let tooltip = document.createElement("div");
        tooltip.className = "drawing-tooltip";
        tooltip.style.position = "fixed";
        tooltip.style.backgroundColor = "rgba(0,0,0,0.7)";
        tooltip.style.color = "white";
        tooltip.style.padding = "5px 10px";
        tooltip.style.borderRadius = "4px";
        tooltip.style.fontSize = "12px";
        tooltip.style.pointerEvents = "none";
        document.body.appendChild(tooltip);

        // 更新提示信息
        view.on("pointer-move", function (event) {
          tooltip.style.left = (event.x + 10) + "px";
          tooltip.style.top = (event.y + 10) + "px";

          switch (geometryType) {
            case 'polygon':
              tooltip.textContent = "点击添加顶点，双击完成";
              break;
            case 'rectangle':
              tooltip.textContent = "点击第一个角点，再点击对角点";
              break;
            case 'circle':
              tooltip.textContent = "点击中心点，再点击确定半径";
              break;
          }
        });

        // 根据不同的绘图类型使用不同的事件处理
        switch (geometryType) {
          case 'polygon':
            action.on(["draw-complete"],
              function (event) {
                console.log('多边形事件:', event.type, event);
                if (event.type === "draw-complete") {
                  // 创建最终的边形几何对象
                  const geometry = {
                    type: "polygon",
                    rings: [event.vertices],
                    spatialReference: view.spatialReference
                  };
                  // 添加最终图形并高亮点
                  addFinalGraphic(geometry);
                  // 重置绘图状态
                  activeAction = null;
                  view.container.style.cursor = "default";
                  // 移除提示信息
                  const tooltip = document.querySelector(".drawing-tooltip");
                  if (tooltip) {
                    document.body.removeChild(tooltip);
                  }
                }
              });
            break;

          case 'rectangle':
            action.on(["vertex-add", "draw-complete"],
              function (event) {
                console.log('矩形事件:', event.type, event);
                // 只在绘制完成时处理
                if (event.type === "draw-complete") {
                  const [start, end] = event.vertices;
                  const rings = [
                    [start[0], start[1]],
                    [end[0], start[1]],
                    [end[0], end[1]],
                    [start[0], end[1]],
                    [start[0], start[1]]
                  ];
                  // 创建最终的矩形几何对象
                  const geometry = {
                    type: "polygon",
                    rings: [rings],
                    spatialReference: view.spatialReference
                  };
                  // 添加最终图形并高亮点
                  addFinalGraphic(geometry);
                  // 重置绘图状态
                  activeAction = null;
                  view.container.style.cursor = "default";
                  // 移除提示信息
                  const tooltip = document.querySelector(".drawing-tooltip");
                  if (tooltip) {
                    document.body.removeChild(tooltip);
                  }
                }
              });
            break;

          case 'circle':
            action.on(["vertex-add", "draw-complete"],
              function (event) {
                console.log('圆形事件:', event.type, event);
                // 只在绘制完成时处理
                if (event.type === "draw-complete") {
                  const center = event.vertices[0];
                  const end = event.vertices[1];
                  const radius = Math.sqrt(
                    Math.pow(end[0] - center[0], 2) +
                    Math.pow(end[1] - center[1], 2)
                  );

                  // 生成圆形点集
                  const numPoints = 64;
                  const rings = [];
                  for (let i = 0; i <= numPoints; i++) {
                    const angle = (i / numPoints) * 2 * Math.PI;
                    const x = center[0] + radius * Math.cos(angle);
                    const y = center[1] + radius * Math.sin(angle);
                    rings.push([x, y]);
                  }
                  // 创建最终的圆形几何对象
                  const geometry = {
                    type: "polygon",
                    rings: [rings],
                    spatialReference: view.spatialReference
                  };
                  // 添加最终图形并高亮点
                  addFinalGraphic(geometry);
                  // 重置绘图状态
                  activeAction = null;
                  view.container.style.cursor = "default";
                  // 移除提示信息
                  const tooltip = document.querySelector(".drawing-tooltip");
                  if (tooltip) {
                    document.body.removeChild(tooltip);
                  }
                }
              });
            break;
        }

        // 添加取消绘制处理
        view.on("click", function (event) {
          if (event.button === 2 && activeAction) { // 右键点击
            activeAction.complete();
            activeAction = null;
            view.container.style.cursor = "default";
          }
        });

        // 添加双击事件监听
        view.on("double-click", function (event) {
          console.log('双击事件触发');
          if (activeAction && geometryType === 'polygon') {
            activeAction.complete();
          }
        });
      }

      // 添加键盘事件监听，用于取消绘制
      document.addEventListener("keydown", function (event) {
        if (event.key === "Escape" && activeAction) {
          activeAction.complete();
          activeAction = null;
          view.container.style.cursor = "default";
        }
      });

      // 选择点
      function selectPoints(geometry) {
        console.log('开始选择点理');
        // 转换几何对象到 WGS84
        const polygon = convertToWGS84(geometry);
        console.log('转换后的多边形:', {
          rings: polygon.rings,
          spatialReference: polygon.spatialReference
        });

        // 重置所有点的颜色
        pointsLayer.graphics.forEach(function (graphic) {
          graphic.symbol = {
            type: "simple-marker",
            color: "red",
            size: 6
          };
        });

        // 高亮选中点
        pointsLayer.graphics.forEach(function (graphic) {
          try {
            if (polygon && graphic.geometry) {
              const point = graphic.geometry;
              // 使用 contains 检查点是否在多边形内
              const isInside = geometryEngine.contains(polygon, point);

              console.log('检查点坐标:', [point.longitude, point.latitude]);
              console.log('检查结果:', isInside);

              if (isInside) {
                console.log('找到在区域内的点:', graphic.attributes);
                graphic.symbol = {
                  type: "simple-marker",
                  color: "yellow",
                  size: 8,
                  outline: {
                    color: [255, 170, 0],
                    width: 1
                  }
                };
              } else {
                // 重置未选中点的样式
                graphic.symbol = {
                  type: "simple-marker",
                  color: "red",
                  size: 6
                };
              }
            }
          } catch (error) {
            console.error('几何计算错误:', error.message);
            console.log('错误详情:', error);
            console.log('点信息:', {
              longitude: graphic.geometry.longitude,
              latitude: graphic.geometry.latitude,
              type: graphic.geometry.type,
              spatialReference: graphic.geometry.spatialReference?.wkid
            });
            console.log('多边形信息:', {
              rings: polygon.rings,
              type: polygon.type,
              spatialReference: polygon.spatialReference?.wkid
            });
          }
        });

        // 输出处理完成信息
        console.log('点选择处理完成');
      }

      // 清除图形
      function clearGraphics() {
        // 如果有活动的绘图操作，先取消它
        if (activeAction) {
          activeAction.complete();
          activeAction = null;
        }

        // 清除所有图层上的图形
        graphicsLayer.removeAll();
        view.graphics.removeAll();

        // 重置的样式
        pointsLayer.graphics.forEach(function (graphic) {
          graphic.symbol = {
            type: "simple-marker",
            color: "red",
            size: 6
          };
        });

        // 重置鼠标样式
        view.container.style.cursor = "default";

        // 移除可能存在的提示
        const tooltip = document.querySelector(".drawing-tooltip");
        if (tooltip) {
          document.body.removeChild(tooltip);
        }
      }

      // 生成随机点
      generateRandomPoints();

      // 绑定按钮事件
      view.when(function () {
        // 确保视图和所有组件都加载完成
        console.log("View is ready");

        document.getElementById("btnPolygon").onclick = function () {
          console.log("Activating polygon tool");
          activateDrawTool("polygon");
        };
        document.getElementById("btnRectangle").onclick = function () {
          console.log("Activating rectangle tool");
          activateDrawTool("rectangle");
        };
        document.getElementById("btnCircle").onclick = function () {
          console.log("Activating circle tool");
          activateDrawTool("circle");
        };
        document.getElementById("btnClear").onclick = function () {
          console.log("Clearing graphics");
          clearGraphics();
        };
      });

      // 添加错误处理
      view.when(function () {
        console.log("Map view is ready");
      }, function (error) {
        console.error("Error loading view:", error);
      });

      // 添加最终图形并高亮点的函数
      function addFinalGraphic(geometry) {
        try {
          console.log('绘制完成，处理图形');
          // 转换绘制的几何对象到 WGS84
          const convertedGeometry = convertToWGS84(geometry);

          // 创建图形
          const graphic = new Graphic({
            geometry: convertedGeometry,
            symbol: {
              type: "simple-fill",
              color: [51, 51, 204, 0.2],
              outline: {
                color: [51, 51, 204],
                width: 1
              }
            }
          });

          console.log('图形创建完成，准备添加到图层');
          graphicsLayer.add(graphic);

          // 直接执行点选择
          selectPoints(convertedGeometry);
        } catch (error) {
          console.error('处理绘制结果时出错:', error.message, error.stack);
          console.log('输入的几何对象:', geometry);
        }
      }
    });
  </script>
</head>

<body>
  <!-- 地图容器 -->
  <div id="viewDiv"></div>
  <!-- 工具栏 -->
  <div class="tool-bar">
    <div class="instructions">
      <p>多边形：点击添加顶点，双击完成</p>
      <p>矩形：点击两个对角点</p>
      <p>圆形：点击中心点和半径点</p>
      <p>按ESC或右键取消绘制</p>
    </div>
    <button id="btnPolygon">多边形选择</button>
    <button id="btnRectangle">矩形选择</button>
    <button id="btnCircle">圆形选择</button>
    <button id="btnClear">清</button>
  </div>
</body>

</html>